package com.bistu.openlab.uofspreadsheet.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/*
 *@author xiaoguang.gao@oracle.com
 *@version 2013-5-8 
 */
public class XmlDomHelper {
	/**
	 * 
	 * @param stream
	 * @return
	 */
	public static Document GetDocFromInputStream(InputStream stream) {
		Document doc = null;
		SAXReader reader = new SAXReader();
		try {
			doc = reader.read(stream);
		} catch (DocumentException e) {
			e.printStackTrace();
		}

		return doc;
	}
	/**
	 * 
	 * @param xmlFile
	 * @return
	 */
	public static Document GetDomFromXmlFile(File xmlFile){
		Document doc = null;
		if(xmlFile.exists()){
			SAXReader reader = new SAXReader();
			try {
				doc = reader.read(xmlFile);
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		}
		return doc;
	}
	/**
	 * 
	 * @param xmlStr
	 * @return
	 */
	public static Document getDomFromXmlStr(String xmlStr)
	{
		Document doc = null;// parse the xml file
		try {
			doc = DocumentHelper.parseText(xmlStr);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return doc;
	}
	/**
	 * 
	 * @param doc
	 * @param outFile
	 */
	public static void WriteDocment(Document doc,File outFile){
		String path = outFile.getAbsolutePath();
		int lastSlash = path.lastIndexOf(File.separator);
		path = path.substring(0, lastSlash);
		File dir = new File(path);
		if(!dir.exists())dir.mkdirs();
		try {
			XMLWriter output = new XMLWriter(new FileWriter(outFile));
			output.write(doc);
			output.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	/**
	 * 
	 * @param node
	 * @param key
	 * @return
	 */
	public static String GetAttributeValue(Element node,String key){
		String ret = "";
		if(node!=null){
			Attribute att = node.attribute(key);
			if(att!=null){
				ret = att.getText();
			}
		}
		return ret;
	}
	/**
	 * create document by element
	 * @param root
	 * @return
	 */
	public static Document GenerateDocumentByRootElement(Element root){
		Document doc = DocumentHelper.createDocument();
		doc.add(root);
		return doc;
	}
}
